import React from 'react';
import { Link } from 'react-router-dom';
import SelectAddress from './../../common/select_address/index.js';
import CascadeMultiSelect from 'uxcore/lib/CascadeMultiSelect';
import { Dialog ,Form,Radio,Checkbox } from 'element-react';
import { DatePicker } from 'element-react';
import { Select,Table,Pagination,Tag,Icon } from 'element-react';
import { Input,Button,MessageBox ,Layout} from 'element-react';
import axios from 'axios';
import Top from '../../top/index.js';
import Nav from '../../nav/index.js';
import './index.css';
import util from '../../../assets/js/util.js';

class ServiceHouseSend extends React.Component{
	constructor(props) {
		super(props)
		this.state = {
		    dialogVisible2: false,
		 	dialogVisible3: false,
		 	page:'',
            pageStart:'',
            pageEnd:'',
		 	exportValue:1,
            substation: [{label:'请选择',value:0}],//分站
            pkgstation: [{label:'请选择',value:0}],//分拣中心
            svcstation: [{label:'请选择',value:0}],//服务亭
			exportFields:["分站", "服务亭", "交货单号", "提交时间", "提交员工", "提交总量", "运输净重", "交运时间", "订单状态", "品类重量", "品类"],
			totalPage:'', //总页数
			curPage:1, //当前页
			total:0, //数据总数
			value:1,
			startDate:null,
			endDate:null,
			orderStatusOptions: [
			{
				value: '',
				label: '请选择'
			},{
				value: '1',
				label: '提交成功'
			}, {
				value: '2',
				label: '接单成功'
			},{
				value: '3',
				label: '取货成功'
			},{
				value: '4',
				label: '验货成功'
			},{
				value: '5',
				label: '结算成功'
			}],
			orderStatus:'', //订单状态选中值
			checkboxData:[{ //导出字段数据
				name:'分站',
				type:'substationName'
			},{
				name:'服务亭',
				type:'houseName'
			},{
				name:'交货单号',
				type:'orderNum'
			},{
				name:'提交时间',
				type:'ctime'
			},{
				name:'提交员工',
				type:'operateName'
			},{
				name:'提交总量',
				type:'orderDeliveryWeight'
			},{
				name:'运输净重',
				type:'netWeight'
			},{
				name:'交运时间',
				type:'orderShipmentCtime'
			},{
				name:'订单状态',
				type:'orderStatus'
			},{
	            name:'品类重量',
	            type:'weight'
            },{
	            name:'品类',
	            type:'recycleTypeTitle'
            }],
			recycleOrderList: [], //表格数据
			subId: 0,
            pkgId: 0,
            houseId: 0,
            subchecking: true,
	        pkgchecking: true,
	        subIndex: 0,
	        pkgIndex: 0,
			recycleOrderNum:'', //交货单号
			orderShipmentNo:'', //交运单号
			driverName:'', //转运司机
			orderRecycleWeightStart:'', //运输净重Start
			orderRecycleWeightEnd:'', //运输净重End
			columns: [
				{
					label:'序号',
					width: 150,
		        	type: 'index'
		        },
				{
					label: "分站",
					prop: "substationName",
					width: 180,
					render: function(data){
					return (
					<span>
						<span>{data.substationName}</span>
					</span>)
					}
				},
				{
					label: "服务亭",
					prop: "houseName",
					width: 160,
					render: function(data){
					return (
						<span>
							<span>{data.houseName}</span>
						</span>
					)
					}
				},
				{
					label: "交货单号",
					prop: "orderNum",
					width: 200,
					render: function(data){
					return (
						<span>
							<span title={data.orderNum}>{data.orderNum}</span>
						</span>
					)
					}
				},
				{
					label: '转运司机',
					prop: 'driverName',
					width: 160,
					render: function(data){
					return (
						<span>
							<span>{data.driverName}</span>
						</span>
					)
					}
				},
				{
					label: "交运单号",
					prop: "orderShipmentNo",
					width: 200,
					render: function(data){
					return (
						<span>
							<span title={data.orderShipmentNo}>{data.orderShipmentNo}</span>
						</span>
					)
					}
				},
				{
					label: "提交时间",
					prop: "ctime",
					width: 160,
					render: function(data){
					return (
						<span>
							<span>{util.getDateTime(data.ctime)}</span>
						</span>
					)
					}
				},
				{
					label: "提交员工",
					prop: "operateName",
					width: 160,
					render: function(data){
					return (
						<span>
							<span>{data.operateName}</span>
						</span>
					)
					}
				},
				{
					label: "提交总重(kg)",
					prop: "orderDeliveryWeight",
					width: 160,
					render: function(data){
					return (
						<span>
							<span>{data.orderDeliveryWeight/1000}</span>
						</span>
					)
					}
				},
				{
					label: "运输净重(kg)",
					prop: "netWeight",
					width: 160,
					render: function(data){
					return (
						<span>
							<span>{data.netWeight/1000}</span>
						</span>
					)
					}
				},
				{
					label: "交运时间",
					prop: "orderShipmentCtime",
					width: 160,
					render: function(data){
					return (
						<span>
							<span>{util.getDateTime(data.orderShipmentCtime)}</span>
						</span>
					)
					}
				},
				{
					label: "订单状态",
					prop: "orderStatus",
					width: 160,
					render: function(data){
					return (
						<span>
							<span>{util.setOrderStatus2(data.orderStatus)}</span>
						</span>
					)
					}
				},
				{
					label: "操作",
					prop: "operate",
					width: 200,
					render: function(data){
					return (
						<span>
							<Link to = {'/viewSend/' + data.orderNum} target="_blank"> 查看 </Link>
						</span>
					)
					}
				}
			]
		}
		this.substationChange = this.substationChange.bind(this);
        this.pkgstationChange = this.pkgstationChange.bind(this);
        this.svcstationChange = this.svcstationChange.bind(this);
        this.selectCheckbox = this.selectCheckbox.bind(this);
	}

	onChange(key,value) {
		this.state[key] = value;
		this.forceUpdate();
	}

	// 选择全部记录还是当前页记录
	onExportChange(e) {
		this.setState({
			exportValue: e
		});
	}

	componentDidMount() {
		this.getData(1);
		this.getAllId();
	}

	// 获取所有分站id
    getAllId() {
        //数据获取
        axios.post('count/count/subsandpkgs').then((res) => {
            //分站列表
            const substation = new Array(res.data.data.length);

            res.data.data.forEach((item, index) => {
                substation[index] = {
                    value: item.id,
                    label: item.name
                }
            });
            substation.unshift({value:"",label:"请选择分站"});
            this.setState({
                substation:substation
            });
        }).catch((err) => {
            console.log(err);
        });
    }

    //分站change事件
    substationChange = (val, option) => {
        this.setState({subId: val});
        var params = new URLSearchParams();
        params.append('subId', val);
        axios.post('count/count/selectpkgsbysubid', params)
            .then((res) => {
                const pkgstation = new Array(res.data.data.length);
                res.data.data.forEach((item, index) => {
                    pkgstation[index] = {
                        value: item.id,
                        label: item.siteName
                    }
                });
                pkgstation.unshift({value:"",label:"请选择分拣中心"});
                this.setState({pkgstation: pkgstation})
            })
            .catch((err) => {
                console.log(err)
            });
    };

    //分拣中心change事件
    pkgstationChange = (val, option) => {
        this.setState({pkgId: val});
        var params = new URLSearchParams();
        params.append('pkgId', val);
        axios.post('count/count/selecthousesbypkgid', params)
            .then((res) => {
                console.log(res);
                const svcstation = new Array(res.data.data.length);
                res.data.data.forEach((item, index) => {
                    svcstation[index] = {
                        value: item.id,
                        label: item.nickname
                    }
                });
                svcstation.unshift({value:"",label:"请选择服务亭"});
                this.setState({svcstation: svcstation})
            })
            .catch((err) => {
                console.log(err)
            });
    };

    //服务亭change事件
    svcstationChange = (val, option) => {
        this.setState({houseId: val});
    };

	//请求列表数据
	getData(curPage){
		var params = new URLSearchParams();
		let startDate,endDate;

		if(this.state.startDate){
			startDate = util.formatDate(this.state.startDate);
		}else{
			startDate = '';
		}
		if(this.state.endDate){
			endDate = util.formatDate(this.state.endDate);
		}else{
			endDate = '';
		}

		params.append('startDate', startDate);
		params.append('endDate', endDate);
		params.append('substationId',this.state.subId);
		params.append('packageId',this.state.pkgId);
		params.append('houseId',this.state.houseId);
		params.append('orderStatus', this.state.orderStatus);
		params.append('orderRecycleWeightStart', this.state.orderRecycleWeightStart);
		params.append('orderRecycleWeightEnd', this.state.orderRecycleWeightEnd);
		params.append('driverName', this.state.driverName);
		params.append('recycleOrderNum', this.state.recycleOrderNum);
		params.append('orderShipmentNo', this.state.orderShipmentNo);
		params.append('page', curPage);
		params.append('size', 20);

		axios.post('/count/countranking/getRecycleOrderDelivery', params).then((data) => {
			console.log(data)
			let res = data.data;
			if (res.code == 0) {
				
				this.setState({
					curPage:res.data.curPage,
					totalPage:res.data.totalPage,
					total:res.data.total,
					recycleOrderList: res.data.recycleOrderList
				})
			}else if(res.code == -111){
				MessageBox.alert(res.msg);
			} else {
				this.props.history.push('/login')
			}
		}).catch((e) => {
			console.log(e)
		})
	}

	//搜索
	handClick(event) {
		event.preventDefault();
		this.getData(1);
	}

	//选择导出字段
	selectCheckbox(e){
		this.setState({
			exportFields:e
		})
	}

	//确定导出
	exportSure(){
		var _page = '';
		var fileds = [];
		let pageEnd = '';


		let startDate,endDate;

		if(this.state.startDate){
			startDate = util.formatDate(this.state.startDate);
		}else{
			startDate = '';
		}
		if(this.state.endDate){
			endDate = util.formatDate(this.state.endDate);
		}else{
			endDate = '';
		}

		if(this.state.exportValue == 1){
			_page = '';
		}else if(this.state.exportValue == 2){
			_page = this.state.curPage;
		}else if(this.state.exportValue == 3){
            _page = this.state.pageStart;
            pageEnd = this.state.pageEnd;
        }

		let checkboxData = this.state.checkboxData;
		let exportFields = this.state.exportFields;
		checkboxData.forEach((item,index)=>{
			exportFields.forEach((subItem,subIndex)=>{
				if(item.name == subItem){
					fileds.push(item.type)
				}
			})
		})

		if(fileds.length < 2) return alert('请至少勾选两项');


		window.open('/count/countranking/getrecycleorderdeliveryExcel?page=' + _page 
			+ '&pageEnd=' + pageEnd + '&fields=' + fileds.join(',')
			+'&substationId='+this.state.subId+'&houseId='+this.state.houseId
			+'&startDate='+startDate+'&endDate='+endDate
			+'&packageId='+this.state.pkgId
			+'&orderStatus='+this.state.orderStatus
			+'&orderShipmentNo='+this.state.orderShipmentNo
			+'&orderRecycleWeightEnd='+this.state.orderRecycleWeightEnd
			+'&recycleOrderNum='+this.state.recycleOrderNum
			+'&orderRecycleWeightStar='+this.state.orderRecycleWeightStart
			+'&driverName='+this.state.driverName);
	}																																																																																												

	//导出弹框
	export(){
		this.setState({
			dialogVisible3: true
		})
	}

	//请求分页数据
	currentPageChange(value){
		//请求当前页
		this.getData(value)
	}

	render(){
		return (
			<div className="main_send">
			    <Top/>
                <Nav serviceSend='active'/>
				<div className="contain">
					<div className="top_top1">
					    <Layout.Row gutter="0" style={{marginTop:'40px'}}>
								<div className="source boxone">
									<div className="block">
										<span className="demo">日期：</span>
										<DatePicker
											value={this.state.startDate}
											placeholder="选择日期"
											onChange={date=>{
												this.setState({startDate: date})
											}}
										/>
										<span className="demo margin">至 </span>
										<DatePicker
											value={this.state.endDate}
											placeholder="选择日期"
											onChange={date=>{
												this.setState({endDate: date})
											}}
										/>
									</div>
								</div>

								<div className="box">
								     <span className="demo">分站：</span>
									 <SelectAddress

		                                value='请选择分站'
		                               
		                                options={this.state.substation}
		                                clsname="slct_substation"
		                                selChange={this.substationChange}
		                            ></SelectAddress> 
		                        </div>
								<div className="box">
								     <span className="demo">分拣中心：</span>
									 <SelectAddress
		                                value='请选择分拣中心'
		                                options={this.state.pkgstation}
		                                clsname='slct_pkgstation inline'
		                                selChange={this.pkgstationChange}
		                            ></SelectAddress>
								</div>
								<div className="box">
								     <span className="demo">服务亭：</span>
									 <SelectAddress
		                                value='请选择服务亭'
		                                options={this.state.svcstation}
		                                clsname='slct_svcstation inline'
		                                selChange={this.svcstationChange}
		                            ></SelectAddress>
								</div>
								<div className="box">
								    <span className="demo">交货单号：</span>   
								    <Input className="" 
										style={{width:'160px'}} placeholder = "" className="inputt" value={this.state.recycleOrderNum} onChange={this.onChange.bind(this,'recycleOrderNum')}/>
								</div>
								<div className="box">
								    <span className="demo">交运单号：</span>   
								    <Input style={{width:'160px'}} placeholder = "" className="inputt" value={this.state.orderShipmentNo} onChange={this.onChange.bind(this,'orderShipmentNo')}/>
								</div>
								<div className="box">
								    <span className="demo">转运司机：</span>   
								    <Input style={{width:'160px'}} placeholder = "" className="inputt" value={this.state.driverName} onChange={this.onChange.bind(this,'driverName')}/>
								</div>
								<div className="box">	
									<span className="demo">订单状态：</span>   
									<Select value={this.state.orderStatus} onChange={this.onChange.bind(this,'orderStatus')}>
										{
											this.state.orderStatusOptions.map(el => {
											return <Select.Option key={el.value} label={el.label} value={el.value} />
											})
										}
									</Select>
								</div>
								<div className="box">  
									<span className = "demo" > 运输净重：</span>
									<div className="demo">
										<Input placeholder = "" className="bg_color" maxlength="10" value={this.state.orderRecycleWeightStart} onChange={this.onChange.bind(this,'orderRecycleWeightStart')}/>
									</div>
									<span className="demo margin"> Kg至 </span>
									<div className="demo">
										<Input placeholder = "" className="bg_color" maxlength="10" value={this.state.orderRecycleWeightEnd} onChange={this.onChange.bind(this,'orderRecycleWeightEnd')}/>
									</div>
									<span className = "demo"> Kg</span>
								</div>
								<div className="box">
								    <Button type="info" className="out1" onClick={this.export.bind(this)} >
							        	<i class="el-icon-upload mr-6"></i>导出
							        </Button>
									<Button type = "info" className="search0" style={{marginRight:'15px'}} onClick={this.handClick.bind(this)}>
										<i class="el-icon-search mr-6"></i>搜索 
								    </Button>
								</div>
							</Layout.Row>

							<div className="">
							
								<Dialog title = "导出" visible={ this.state.dialogVisible3 }
										onCancel={ () => this.setState({ dialogVisible3: false }) }>

									<Dialog.Body>
										<Form model={this.state.form}>

											<Form.Item label="导出为" labelWidth="120">
												<Select value="1" placeholder="请选择导出方式">
												 <Select.Option label="Excel" value="1"></Select.Option>
												</Select>
											</Form.Item>
											<Form.Item>
												<Radio value="1" checked={this.state.exportValue === 1}
													   onChange={this.onExportChange.bind(this)}>全部记录</Radio>
												<Radio value="2" checked={this.state.exportValue === 2}
													   onChange={this.onExportChange.bind(this)}>当前页记录</Radio>
													   <Radio value="3" checked={this.state.exportValue === 3}
	                                               onChange={this.onExportChange.bind(this)}>
	                                            <span >从</span>
	                                             <Input className="exportInput"  onChange={(el)=>{this.setState({pageStart:el})}}/><span>至</span>
	                                            <Input className="exportInput"  onChange={(el)=>{this.setState({pageEnd:el})}}/><span>页</span>
	                                            </Radio>
											</Form.Item>

											<Form.Item label="导出字段" labelWidth="120">

											</Form.Item>

											<Form.Item>
												<div className="check is-checked">
													<Checkbox.Group value={this.state.exportFields} onChange={ this.selectCheckbox.bind(this) }>
	                                                    {
	                                                        this.state.checkboxData.map((item,index)=>{
	                                                            return <Checkbox key={index} label={item.name}></Checkbox>
	                                                        })
	                                                    }
													</Checkbox.Group>
												</div>
											</Form.Item>
										</Form>
									</Dialog.Body>

									<Dialog.Footer className="dialog-footer">
										<Button className="can" onClick={ () => this.setState({ dialogVisible3: false }) }>取 消</Button>
										<Button className="sur" type="primary" onClick={ this.exportSure.bind(this) }>确 定</Button>
									</Dialog.Footer>
								</Dialog>

						    </div>
					
					</div>
					
					<div className="table_3 tablebar">
						<Table
							style={{width: '100%'}}
							columns={this.state.columns}
							data={this.state.recycleOrderList}
							total={this.state.total}
							border={true}
							highlightCurrentRow={true}
						/>
						{<Pagination layout="total,prev, pager, next, jumper"
						total={this.state.total}
						pageSize={20} 
						currentPage={this.state.curPage}
						onCurrentChange={this.currentPageChange.bind(this)}
						/>}
					</div>
				</div>
			</div>
		);
	}
}

export default ServiceHouseSend;